<template>
  <div class="user-registration-example">
    <h2>用户注册表单示例</h2>
    
    <!-- 表单设计器（仅在开发环境使用） -->
    <div v-if="showDesigner" class="form-designer-container">
      <VFormDesigner ref="formDesigner" heigth="600px"></VFormDesigner>
      <div class="designer-actions">
        <el-button type="primary" @click="switchToRender">切换到表单渲染器</el-button>
        <el-button @click="loadSampleForm">加载示例表单</el-button>
      </div>
    </div>
    
    <!-- 表单渲染器（实际应用中使用） -->
    <div v-else class="form-render-container">
      <VFormDesigner
        :form-json="formJson" 
        :form-data="formData" 
        :option-data="optionData"
        ref="formRender">
      </VFormDesigner>
      
      <div class="form-actions">
        <el-button type="primary" @click="submitForm">提交注册</el-button>
        <el-button @click="resetForm">重置表单</el-button>
        <el-button @click="switchToDesigner">返回设计器</el-button>
      </div>
      
      <!-- 提交结果展示 -->
      <div v-if="submitResult" class="submit-result">
        <h3>表单提交结果：</h3>
        <pre>{{ JSON.stringify(submitResult, null, 2) }}</pre>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import VFormDesigner from '../components/form-designer/index.vue'


// 控制显示设计器还是渲染器
const showDesigner = ref(true)

// 表单JSON配置
const formJson = reactive({
  widgetList: [],
  formConfig: {
    modelName: "formData",
    refName: "vForm",
    rulesName: "rules",
    labelWidth: 100,
    labelPosition: "top",
    size: "default",
    labelAlign: "label-left-align",
    cssCode: "",
    customClass: "",
    functions: "",
    layoutType: "PC",
    jsonVersion: 3,
    onFormCreated: "",
    onFormMounted: "",
    onFormDataChange: ""
  }
})

// 表单数据
const formData = reactive({})

// 选项数据
const optionData = reactive({
  genderOptions: [
    { label: '男', value: 'male' },
    { label: '女', value: 'female' },
    { label: '其他', value: 'other' }
  ],
  educationOptions: [
    { label: '高中', value: 'highschool' },
    { label: '大专', value: 'college' },
    { label: '本科', value: 'bachelor' },
    { label: '硕士', value: 'master' },
    { label: '博士', value: 'phd' }
  ],
  interestOptions: [
    { label: '阅读', value: 'reading' },
    { label: '音乐', value: 'music' },
    { label: '运动', value: 'sports' },
    { label: '旅行', value: 'travel' },
    { label: '电影', value: 'movies' },
    { label: '编程', value: 'coding' }
  ]
})

// 提交结果
const submitResult = ref(null)

// 组件引用
const formDesigner = ref(null)
const formRender = ref(null)

// 切换到渲染器
const switchToRender = () => {
  if (formDesigner.value) {
    const designJson = formDesigner.value.getFormJson()
    Object.assign(formJson, designJson)
  }
  showDesigner.value = false
}

// 切换到设计器
const switchToDesigner = () => {
  showDesigner.value = true
}

// 提交表单
const submitForm = () => {
  formRender.value.getFormData().then(data => {
    // 表单验证通过
    ElMessage.success('表单验证通过，提交成功！')
    submitResult.value = data
    
    // 实际应用中，这里会发送请求到后端
    // axios.post('/api/register', data)
    //   .then(response => {
    //     ElMessage.success('注册成功！')
    //   })
    //   .catch(error => {
    //     ElMessage.error('注册失败：' + error.message)
    //   })
    
  }).catch(error => {
    // 表单验证失败
    ElMessage.error('表单验证失败：' + error)
  })
}

// 重置表单
const resetForm = () => {
  formRender.value.resetForm()
  submitResult.value = null
}

// 加载示例表单
const loadSampleForm = () => {
  const sampleForm = {
    widgetList: [
      {
        type: "grid",
        category: "container",
        icon: "grid",
        cols: [
          {
            type: "grid-col",
            category: "container",
            icon: "grid-col",
            internal: true,
            span: 8,
            widgetList: [
              {
                type: "radio",
                icon: "radio-field",
                formItemFlag: true,
                options: {
                  name: "gender",
                  label: "性别",
                  labelAlign: "",
                  defaultValue: "",
                  columnWidth: "200px",
                  size: "",
                  displayStyle: "inline",
                  buttonStyle: false,
                  border: false,
                  labelWidth: null,
                  labelHidden: false,
                  disabled: false,
                  hidden: false,
                  optionItems: [
                    {
                      label: "男",
                      value: "male"
                    },
                    {
                      label: "女",
                      value: "female"
                    },
                    {
                      label: "其他",
                      value: "other"
                    }
                  ],
                  required: true,
                  validation: "",
                  validationHint: "",
                  customClass: [],
                  labelIconClass: null,
                  labelIconPosition: "rear",
                  labelTooltip: null,
                  optionItemsSource: "genderOptions"
                },
                id: "gender100001"
              }
            ]
          },
          {
            type: "grid-col",
            category: "container",
            icon: "grid-col",
            internal: true,
            span: 8,
            widgetList: [
              {
                type: "date",
                icon: "date-field",
                formItemFlag: true,
                options: {
                  name: "birthday",
                  label: "出生日期",
                  labelAlign: "",
                  type: "date",
                  defaultValue: "",
                  placeholder: "选择日期",
                  columnWidth: "200px",
                  size: "",
                  labelWidth: null,
                  labelHidden: false,
                  readonly: false,
                  disabled: false,
                  hidden: false,
                  clearable: true,
                  editable: false,
                  format: "yyyy-MM-dd",
                  valueFormat: "yyyy-MM-dd",
                  required: false,
                  validation: "",
                  validationHint: "",
                  customClass: [],
                  labelIconClass: null,
                  labelIconPosition: "rear",
                  labelTooltip: null,
                  startPlaceholder: "",
                  endPlaceholder: "",
                  timeFormat: "HH:mm:ss",
                  butDays: 0,
                  limitStartDate: "",
                  limitEndDate: ""
                },
                id: "birthday100001"
              }
            ]
          },
          {
            type: "grid-col",
            category: "container",
            icon: "grid-col",
            internal: true,
            span: 8,
            widgetList: [
              {
                type: "select",
                icon: "select-field",
                formItemFlag: true,
                options: {
                  name: "education",
                  label: "学历",
                  labelAlign: "",
                  defaultValue: "",
                  placeholder: "请选择学历",
                  columnWidth: "200px",
                  size: "",
                  labelWidth: null,
                  labelHidden: false,
                  disabled: false,
                  hidden: false,
                  clearable: true,
                  filterable: false,
                  allowCreate: false,
                  remote: false,
                  automaticDropdown: false,
                  multiple: false,
                  multipleLimit: 0,
                  optionItems: [
                    {
                      label: "高中",
                      value: "highschool"
                    },
                    {
                      label: "大专",
                      value: "college"
                    },
                    {
                      label: "本科",
                      value: "bachelor"
                    },
                    {
                      label: "硕士",
                      value: "master"
                    },
                    {
                      label: "博士",
                      value: "phd"
                    }
                  ],
                  required: false,
                  validation: "",
                  validationHint: "",
                  customClass: [],
                  labelIconClass: null,
                  labelIconPosition: "rear",
                  labelTooltip: null,
                  optionItemsSource: "educationOptions"
                },
                id: "education100001"
              }
            ]
          }
        ],
        options: {
          name: "栅格布局",
          hidden: false,
          gutter: 12,
          colHeight: null,
          customClass: ""
        },
        id: "grid100004"
      },
      {
        type: "checkbox",
        icon: "checkbox-field",
        formItemFlag: true,
        options: {
          name: "interests",
          label: "兴趣爱好",
          labelAlign: "",
          defaultValue: [],
          columnWidth: "200px",
          size: "",
          displayStyle: "block",
          buttonStyle: false,
          border: false,
          labelWidth: null,
          labelHidden: false,
          disabled: false,
          hidden: false,
          optionItems: [
            {
              label: "阅读",
              value: "reading"
            },
            {
              label: "音乐",
              value: "music"
            },
            {
              label: "运动",
              value: "sports"
            },
            {
              label: "旅行",
              value: "travel"
            },
            {
              label: "电影",
              value: "movies"
            },
            {
              label: "编程",
              value: "coding"
            }
          ],
          required: false,
          validation: "",
          validationHint: "",
          customClass: [],
          labelIconClass: null,
          labelIconPosition: "rear",
          labelTooltip: null,
          optionItemsSource: "interestOptions"
        },
        id: "interests100001"
      },
      {
        type: "textarea",
        icon: "textarea-field",
        formItemFlag: true,
        options: {
          name: "introduction",
          label: "自我介绍",
          labelAlign: "",
          rows: 3,
          defaultValue: "",
          placeholder: "请简单介绍一下自己",
          columnWidth: "200px",
          size: "",
          labelWidth: null,
          labelHidden: false,
          readonly: false,
          disabled: false,
          hidden: false,
          required: false,
          validation: "",
          validationHint: "",
          customClass: [],
          labelIconClass: null,
          labelIconPosition: "rear",
          labelTooltip: null,
          minLength: null,
          maxLength: 300,
          showWordLimit: true
        },
        id: "introduction100001"
      },
      {
        type: "switch",
        icon: "switch-field",
        formItemFlag: true,
        options: {
          name: "agreement",
          label: "同意用户协议",
          labelAlign: "",
          defaultValue: false,
          columnWidth: "200px",
          size: "",
          labelWidth: null,
          labelHidden: false,
          disabled: false,
          hidden: false,
          customClass: [],
          labelIconClass: null,
          labelIconPosition: "rear",
          labelTooltip: null,
          activeText: "是",
          inactiveText: "否",
          activeColor: null,
          inactiveColor: null,
          required: true,
          validation: "",
          validationHint: "请同意用户协议"
        },
        id: "agreement100001"
      }
    ],
    formConfig: {
      modelName: "formData",
      refName: "vForm",
      rulesName: "rules",
      labelWidth: 100,
      labelPosition: "top",
      size: "default",
      labelAlign: "label-left-align",
      cssCode: "",
      customClass: "",
      functions: "export default {\n  onFormCreated(form) {\n    //表单创建完成回调\n    console.log('表单创建完成');\n  },\n  \n  onFormMounted(form) {\n    //表单挂载完成回调\n    console.log('表单挂载完成');\n  },\n  \n  onFormDataChange(field, value, form) {\n    //表单数据变化回调\n    console.log('表单数据变化', field, value);\n  }\n}",
      layoutType: "PC",
      jsonVersion: 3,
      onFormCreated: "",
      onFormMounted: "",
      onFormDataChange: ""
    }
  }
  
  if (formDesigner.value) {
    formDesigner.value.setFormJson(sampleForm)
    ElMessage.success('示例表单已加载')
  }
}

// 组件挂载完成后执行
onMounted(() => {
  // 可以在这里加载保存的表单配置
})
</script>

<style scoped>
.user-registration-example {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #409EFF;
}

.form-designer-container, 
.form-render-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.designer-actions,
.form-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.submit-result {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.submit-result h3 {
  margin-top: 0;
  color: #409EFF;
}

pre {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  overflow: auto;
}
</style>